package com.none.staff.presenter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.none.staff.BuildConfig;
import com.none.staff.R;
import com.none.staff.contract.ISplashContract;
import com.none.staff.managers.SharePreferenceManager;
import com.none.staff.model.ConfigBean;
import com.none.staff.model.Webresources;
import com.none.staff.net.RetrofitUtil;
import com.none.staff.net.interfaces.DownloadFileListener;
import com.none.staff.utils.Constants;
import com.none.staff.view.activitys.HomeActivity;
import com.peter.baselibrary.base.BasePresenter;
import com.peter.baselibrary.utils.AppUtils;
import com.peter.baselibrary.utils.FileUtil;
import com.peter.baselibrary.utils.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashPresenter extends BasePresenter<ISplashContract.ISplashView> implements ISplashContract.ISplashPresenter {

    private Context context;
    private ConfigBean configBean;
    private SharePreferenceManager sharePreferenceManager;
    private List<Webresources> needDownLoadWebresourcesList;
    private List<String> unZipFilePathList;
    private boolean isNeedDownloadApkFile = false;
    private boolean isNeedDownloadClientPackResource = false;
    private int length = 0;
    private boolean isDownloadDone = true;

    public SplashPresenter(Context context) {
        this.context = context;
        sharePreferenceManager = new SharePreferenceManager(context);
    }

    /**
     * @return
     */
    @Override
    public boolean isGoInGuide() {
        String currentVersion = AppUtils.INSTANCE.getVersion(context);
        if (currentVersion != null) {
            if (Integer.valueOf(sharePreferenceManager
                    .getSharedPreferences(Constants.SP_APPLICATION_VERSION)
                    .getString(Constants.SP_APK_VERSION, "0.0").replaceAll("\\.", "")) <
                    Integer.valueOf(currentVersion.replaceAll("\\.", ""))) {
                Objects.requireNonNull(getView()).showGuidePage();
                return true;
            }
        }
        return false;
    }

    /**
     * @param url
     */
    @Override
    public void getConfig(String url) {
        RetrofitUtil.getInstances().getConfig(url, new Callback<ConfigBean>() {
            @Override
            public void onResponse(Call<ConfigBean> call, Response<ConfigBean> response) {
                configBean = response.body();
                assert configBean != null;
                //对象转字符串
                String config = new Gson().toJson(configBean);
                //获取版本号
                String version = configBean.getVersion();
                //创建存储需要下载的资源地址list
                needDownLoadWebresourcesList = new ArrayList<>();
                //获取本地存储的配置信息并转换成对象，用来对比app是否需要更新
                ConfigBean oldConfigBean = new Gson().fromJson(sharePreferenceManager
                        .getSharedPreferences(Constants.SP_CONFIG_SHARED_NAME)
                        .getString(Constants.SP_APPLICATION_CONFIG_CONTENT, ""), ConfigBean.class);
                String oldVersion;
                //判断本地是否存储有配置信息
                if (oldConfigBean != null) {
                    //如果有，对比之前存储的版本号和hashcode来判断是否需要更新
                    oldVersion = oldConfigBean.getVersion();
                    if (!version.isEmpty() && !oldVersion.isEmpty()
                            && (Integer.valueOf(version.replaceAll("\\.", "0"))
                            > Integer.valueOf(oldVersion.replaceAll("\\.", "0")))) {
                        Objects.requireNonNull(getView()).showIsUpgradeDialog();
                        isNeedDownloadApkFile = true;
                    }

                    List<Webresources> oldWebresourcesList = oldConfigBean.getWebresources();
                    List<Webresources> newWebresourceList = configBean.getWebresources();
                    String oldHashcode;
                    String newHashcode;
                    for (int i = 0; i < newWebresourceList.size(); i++) {
                        oldHashcode = oldWebresourcesList.get(i).getHashcode();
                        newHashcode = newWebresourceList.get(i).getHashcode();
                        if (!newHashcode.equals(oldHashcode)) {
                            needDownLoadWebresourcesList.add(newWebresourceList.get(i));
                        }
                    }

                    isNeedDownloadClientPackResource = needDownLoadWebresourcesList != null && needDownLoadWebresourcesList.size() > 0;
                } else {
                    //如果本地没有存储的配置信息 说明用户是第一次安装app所以不要要做apk更新，只需要做client pack resource更新
                    isNeedDownloadApkFile = false;
                    needDownLoadWebresourcesList.addAll(configBean.getWebresources());
                    isNeedDownloadClientPackResource = true;
                }
                sharePreferenceManager
                        .getSharedPreferences(Constants.SP_CONFIG_SHARED_NAME)
                        .putString(Constants.SP_APPLICATION_CONFIG_CONTENT, config);

                LogUtils.INSTANCE.e(version + "  config:      " + config);

//                sharePreferenceManager
//                        .getSharedPreferences(Constants.SP_CONFIG_SHARED_NAME)
//                        .putString(Constants.SP_APPLICATION_CONFIG_CONTENT, config);
                if (getView() != null)
                    getView().getConfigSuccess();
            }

            @Override
            public void onFailure(Call<ConfigBean> call, Throwable t) {
                LogUtils.INSTANCE.e(t.getMessage() + "");
                if (getView() != null)
                    getView().getConfigFailed(context.getResources().getString(R.string.net_error), t.getMessage());
            }
        });
    }

    /**
     * 检查是否更新apk文件
     * 当获取到的配置文件中的version跟本地存储的version不一致，新的version高于本地的version时，返回true，反之则返回false
     *
     * @return 返回检查结果
     */
    @Override
    public boolean checkNativeIsNeedUpgrade() {

        return isNeedDownloadApkFile;
    }

    /**
     *
     */
    @Override
    public void downloadUpgradeAPKFile() {

        RetrofitUtil.getInstances().downLoadApkFile(configBean.getAppUpgradeLink(), new DownloadFileListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish(String localPath) {
                LogUtils.INSTANCE.e("下载完成 ：" + localPath);
                installApk(localPath);
            }

            @Override
            public void onProgress(int currentLength) {
                LogUtils.INSTANCE.d("下载中 ：" + currentLength);
                Objects.requireNonNull(getView()).downloadUpgrade(currentLength);
            }

            @Override
            public void onFailure(String errorMessage) {
                Objects.requireNonNull(getView()).getConfigFailed("APK下载", "下载失败，请检查网络是否可用");
            }

        });
    }

    /**
     *
     */
    @Override
    public void nativeUpgrade() {

    }

    /**
     * @return 返回是否需要更新客户端资源
     */
    @Override
    public boolean checkClientIsNeedUpgrade() {

        return isNeedDownloadClientPackResource;
    }

    /**
     *
     */
    @Override
    public void downloadClientResource() {
        unZipFilePathList = new ArrayList<>();
        downloadResource();
    }

    @Override
    public void verifyPackageLegality() {

    }

    @Override
    public void unZipFile() {

    }

    @Override
    public void saveFile() {

    }

    private void downloadResource() {
        if (needDownLoadWebresourcesList == null)
            return;
        if (length < needDownLoadWebresourcesList.size()) {
            LogUtils.INSTANCE.e("Size:   " + needDownLoadWebresourcesList.size() + "    Length: ==" + length);
            RetrofitUtil.getInstances().downloadWebResource(needDownLoadWebresourcesList.get(length).getZipurl(), new DownloadFileListener() {
                @Override
                public void onStart() {

                }


                @Override
                public void onFinish(String localPath) {
                    LogUtils.INSTANCE.e("下载完成 ：" + localPath);
//                    try {
//                        FileUtil.INSTANCE.unZip(localPath, Constants.getDownloadResourcesFilePath());
                        unZipFilePathList.add(localPath);
                        length++;
                        downloadResource();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
                }

                @Override
                public void onProgress(int currentLength) {
//                    LogUtils.INSTANCE.d("下载中 ：" + currentLength);
                    Objects.requireNonNull(getView()).downloadUpgrade(currentLength);
                }

                @Override
                public void onFailure(String errorMessage) {
                    Objects.requireNonNull(getView()).getConfigFailed("Resource下载", "下载失败，请检查网络是否可用");
                    isDownloadDone = false;
                }
            });
        } else {
            LogUtils.INSTANCE.e("全部下载完成了");
            try {
                for (int i = 0; i < unZipFilePathList.size(); i++) {
                    FileUtil.INSTANCE.unZip(unZipFilePathList.get(i), Constants.getDownloadResourcesFilePath()+"betta"+File.separator);
                    LogUtils.INSTANCE.e("下载路径"+unZipFilePathList.get(i));
                    LogUtils.INSTANCE.e("安装路径"+Constants.getDownloadResourcesFilePath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Objects.requireNonNull(getView()).intoHomePage();

        }
    }

    private void installApk(String apkPath) {
        if (context == null || TextUtils.isEmpty(apkPath)) {
            return;
        }
        File file = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}
